// 环形图片 - 性能优化版本
import { useEffect, useRef } from 'react'
import * as THREE from 'three'
import './App.css'

// 导入GLTFLoader用于加载GLB模型
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { PointerLockControls } from 'three/examples/jsm/controls/PointerLockControls.js';
import Stats from 'three/examples/jsm/libs/stats.module.js';
function App() {
  const containerRef = useRef(null)
  const scrollContainerRef = useRef(null) // 滚动容器的引用

  useEffect(() => {
    const stats = new Stats();
    document.body.appendChild(stats.dom);
    // 创建场景
    const scene = new THREE.Scene()

    // 创建相机
    const camera = new THREE.PerspectiveCamera(
      75, // 视野角度
      window.innerWidth / window.innerHeight, // 宽高比
      0.1, // 近裁剪面
      1000 // 远裁剪面
    )

    // 设置相机初始位置（模拟人眼高度）
    camera.position.set(0, 1.6, 5);

    // 创建渲染器并优化设置
    const renderer = new THREE.WebGLRenderer({
      antialias: true, // 抗锯齿
      alpha: true, // 支持透明背景
      powerPreference: "high-performance" // 优先使用高性能GPU
    })

    // 渲染器基础设置
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // 限制像素比，避免过高分辨率

    // 阴影优化设置
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFShadowMap; // 使用性能更好的阴影类型

    // 渲染优化设置
    renderer.outputColorSpace = THREE.SRGBColorSpace;
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.0;

    // 创建第一人称控制器
    const controls = new PointerLockControls(camera, renderer.domElement);

    // 指针锁定事件监听器
    const onPointerLockChange = () => {
      if (document.pointerLockElement === renderer.domElement) {
        console.log('指针已锁定');
      } else {
        console.log('指针已解锁');
      }
    };

    const onPointerLockError = () => {
      console.error('指针锁定失败');
    };

    // 添加事件监听器
    document.addEventListener('pointerlockchange', onPointerLockChange);
    document.addEventListener('pointerlockerror', onPointerLockError);

    // 点击画布锁定指针
    const onCanvasClick = () => {
      controls.lock();
    };

    renderer.domElement.addEventListener('click', onCanvasClick);

    // 将渲染器添加到容器
    if (containerRef.current) {
      containerRef.current.appendChild(renderer.domElement)
    }

    // 键盘移动控制变量
    const move = { forward: false, backward: false, left: false, right: false, up: false, down: false };
    const velocity = new THREE.Vector3();
    const direction = new THREE.Vector3();
    const moveSpeed = 20.0; // 移动速度

    // 键盘按下事件处理
    const onKeyDown = (e) => {
      switch (e.code) {
        case 'KeyW': move.forward = true; break;
        case 'KeyS': move.backward = true; break;
        case 'KeyA': move.left = true; break;
        case 'KeyD': move.right = true; break;
        case 'Space': move.up = true; e.preventDefault(); break;
        case 'ShiftLeft': move.down = true; break;
        case 'Escape': controls.unlock(); break; // ESC键解锁指针
      }
    };

    // 键盘释放事件处理
    const onKeyUp = (e) => {
      switch (e.code) {
        case 'KeyW': move.forward = false; break;
        case 'KeyS': move.backward = false; break;
        case 'KeyA': move.left = false; break;
        case 'KeyD': move.right = false; break;
        case 'Space': move.up = false; break;
        case 'ShiftLeft': move.down = false; break;
      }
    };

    // 添加键盘事件监听器
    document.addEventListener('keydown', onKeyDown);
    document.addEventListener('keyup', onKeyUp);

    // 创建基础场景对象组
    const baseObrit = new THREE.Object3D()
    baseObrit.position.set(0, 0, 0)
    scene.add(baseObrit)

    // 创建模型场景对象组
    const modelObrit = new THREE.Object3D()
    modelObrit.position.set(0, 0, 0)
    scene.add(modelObrit)

    // 性能优化：使用InstancedMesh创建星星群
    function createOptimizedStars() {
      const starCount = 200;
      const geometry = new THREE.SphereGeometry(0.25, 12, 8); // 减少几何体复杂度
      const material = new THREE.MeshBasicMaterial({
        color: 0xfbc017,
        // 使用BasicMaterial替代PhongMaterial以提升性能
      });

      // 使用InstancedMesh批量渲染星星
      const instancedStars = new THREE.InstancedMesh(geometry, material, starCount);

      // 设置每个实例的位置
      const matrix = new THREE.Matrix4();
      for (let i = 0; i < starCount; i++) {
        const x = THREE.MathUtils.randFloatSpread(100);
        const y = THREE.MathUtils.randFloatSpread(100);
        const z = THREE.MathUtils.randFloatSpread(100);

        matrix.setPosition(x, y, z);
        instancedStars.setMatrixAt(i, matrix);
      }

      // 更新实例矩阵
      instancedStars.instanceMatrix.needsUpdate = true;

      // 禁用阴影以提升性能
      instancedStars.castShadow = false;
      instancedStars.receiveShadow = false;

      baseObrit.add(instancedStars);
    }

    // 调用优化后的星星创建函数
    createOptimizedStars();

    // GLB模型加载优化
    const gltfLoader = new GLTFLoader();
    let loadedModel = null;

    gltfLoader.load(
      '/glbExample/quit.glb',
      (gltf) => {
        console.log('GLB模型加载成功:', gltf);
        loadedModel = gltf.scene;
        loadedModel.position.set(0, 0, 0);

        // 优化模型材质和阴影设置
        loadedModel.traverse((child) => {
          if (child.isMesh) {
            // 只对主要模型启用阴影
            child.castShadow = true;
            child.receiveShadow = true;

            if (child.material) {
              // 材质优化设置
              if (child.material.type === 'MeshStandardMaterial') {
                child.material.roughness = 0.8;
                child.material.metalness = 0.1;
              }

              // 启用材质缓存
              child.material.needsUpdate = true;

              // 如果材质有贴图，优化贴图设置
              if (child.material.map) {
                child.material.map.generateMipmaps = true;
                child.material.map.minFilter = THREE.LinearMipmapLinearFilter;
                child.material.map.magFilter = THREE.LinearFilter;
              }
            }
          }
        });

        modelObrit.add(loadedModel);
      },
      (progress) => {
        const percentComplete = (progress.loaded / progress.total) * 100;
        console.log(`GLB模型加载进度: ${percentComplete.toFixed(2)}%`);
      },
      (error) => {
        console.error('GLB模型加载失败:', error);
      }
    );

    // 图片纹理加载优化
    const loader = new THREE.TextureLoader();
    const imageCount = 12;
    const radius = 10;
    const group = new THREE.Group();
    const maxSize = 3;

    // 纹理缓存对象
    const textureCache = new Map();

    // 优化图片加载函数
    function loadOptimizedImages() {
      for (let i = 0; i < imageCount; i++) {
        const imgPath = `/images/${i + 1}.jpg`;

        loader.load(imgPath, (texture) => {
          // 纹理优化设置
          texture.wrapS = THREE.RepeatWrapping;
          texture.repeat.x = -1;
          texture.generateMipmaps = true;
          texture.minFilter = THREE.LinearMipmapLinearFilter;
          texture.magFilter = THREE.LinearFilter;

          // 缓存纹理
          textureCache.set(imgPath, texture);

          const image = texture.image;
          const imageWidth = image.width;
          const imageHeight = image.height;
          const aspectRatio = imageWidth / imageHeight;

          // 计算平面尺寸
          let planeWidth, planeHeight;
          if (aspectRatio > 1) {
            planeWidth = maxSize;
            planeHeight = maxSize / aspectRatio;
          } else {
            planeHeight = maxSize;
            planeWidth = maxSize * aspectRatio;
          }

          // 使用BasicMaterial提升性能
          const material = new THREE.MeshBasicMaterial({
            map: texture,
            side: THREE.DoubleSide,
            transparent: true,
            alphaTest: 0.1
          });

          // 创建平面几何体
          const plane = new THREE.Mesh(
            new THREE.PlaneGeometry(planeWidth, planeHeight),
            material
          );

          // 设置位置
          const angle = (i / imageCount) * Math.PI * 2;
          plane.position.set(
            Math.cos(angle) * radius,
            0,
            Math.sin(angle) * radius
          );
          plane.lookAt(0, 0, 0);

          // 禁用阴影以提升性能
          plane.castShadow = false;
          plane.receiveShadow = false;

          group.add(plane);
        });
      }
    }

    // 调用优化后的图片加载函数
    loadOptimizedImages();

    group.position.set(0, 2, 0);
    baseObrit.add(group)

    // 设置场景背景
    scene.background = new THREE.Color(0x000)

    // 优化地面创建
    function createOptimizedGround() {
      const planeSize = 40;

      loader.load('./checker.png', (texture) => {
        // 纹理优化设置
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.RepeatWrapping;
        texture.magFilter = THREE.NearestFilter;
        texture.colorSpace = THREE.SRGBColorSpace;
        texture.generateMipmaps = true;

        const repeats = planeSize / 2;
        texture.repeat.set(repeats, repeats);

        const planeGeo = new THREE.PlaneGeometry(planeSize, planeSize);
        const planeMat = new THREE.MeshLambertMaterial({ // 使用Lambert材质提升性能
          map: texture,
          side: THREE.DoubleSide,
        });

        const mesh = new THREE.Mesh(planeGeo, planeMat);
        mesh.rotation.x = Math.PI * -.5;
        mesh.receiveShadow = true;
        scene.add(mesh);
      });
    }

    // 调用优化后的地面创建函数
    createOptimizedGround();

    // 优化光照设置
    function setupOptimizedLighting() {
      // 主点光源（降低强度）
      const pointLight = new THREE.PointLight(0xFFFFFF, 50); // 大幅降低强度
      pointLight.position.set(0, 10, 0);
      pointLight.distance = 50; // 设置光照范围
      pointLight.decay = 2; // 设置衰减

      // 优化阴影设置
      pointLight.castShadow = true;
      pointLight.shadow.mapSize.width = 1024; // 降低阴影贴图分辨率
      pointLight.shadow.mapSize.height = 1024;
      pointLight.shadow.camera.near = 0.1;
      pointLight.shadow.camera.far = 50;
      pointLight.shadow.bias = -0.0001;

      scene.add(pointLight);

      // 环境光（提供基础照明）
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
      scene.add(ambientLight);

      // 添加方向光作为主要光源
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      directionalLight.position.set(5, 10, 5);
      directionalLight.castShadow = true;

      // 优化方向光阴影设置
      directionalLight.shadow.mapSize.width = 1024;
      directionalLight.shadow.mapSize.height = 1024;
      directionalLight.shadow.camera.near = 0.1;
      directionalLight.shadow.camera.far = 50;
      directionalLight.shadow.camera.left = -20;
      directionalLight.shadow.camera.right = 20;
      directionalLight.shadow.camera.top = 20;
      directionalLight.shadow.camera.bottom = -20;

      scene.add(directionalLight);
    }

    // 调用优化后的光照设置函数
    setupOptimizedLighting();

    // 窗口大小变化处理函数
    const handleResize = () => {
      camera.aspect = window.innerWidth / window.innerHeight
      camera.updateProjectionMatrix()
      renderer.setSize(window.innerWidth, window.innerHeight)
      renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) // 限制像素比
    }

    window.addEventListener('resize', handleResize);

    // 性能监控变量
    let frameCount = 0;
    let lastFPSUpdate = performance.now();

    // 优化渲染循环
    let prevTime = performance.now();
    const maxDelta = 1 / 30; // 限制最大帧时间，避免大幅跳跃

    function animate() {
      requestAnimationFrame(animate)

      const time = performance.now();
      let delta = (time - prevTime) / 1000;

      // 限制delta时间，避免卡顿时的大幅跳跃
      delta = Math.min(delta, maxDelta);

      // 只有在指针锁定时才处理移动计算
      if (controls.isLocked) {
        // 应用阻尼（优化计算）
        const dampingFactor = 10.0 * delta;
        velocity.x -= velocity.x * dampingFactor;
        velocity.z -= velocity.z * dampingFactor;
        velocity.y -= velocity.y * dampingFactor;

        // 计算移动方向
        direction.z = Number(move.forward) - Number(move.backward);
        direction.x = Number(move.right) - Number(move.left);
        direction.y = Number(move.up) - Number(move.down);
        direction.normalize();

        // 应用移动速度
        if (move.forward || move.backward) velocity.z -= direction.z * moveSpeed * delta;
        if (move.left || move.right) velocity.x -= direction.x * moveSpeed * delta;
        if (move.up || move.down) velocity.y += direction.y * moveSpeed * delta;

        // 应用移动
        controls.moveRight(-velocity.x * delta);
        controls.moveForward(-velocity.z * delta);

        // 垂直移动
        camera.position.y += velocity.y * delta;

        // 限制相机高度
        camera.position.y = Math.max(0.5, Math.min(camera.position.y, 20));
      }

      // 模型旋转（降低旋转速度）
      modelObrit.rotation.y -= 0.002;

      prevTime = time;

      // 性能监控（可选）
      frameCount++;
      if (time - lastFPSUpdate > 1000) {
        const fps = frameCount;
        console.log(`FPS: ${fps}`);
        frameCount = 0;
        lastFPSUpdate = time;
      }

      // 渲染场景
      renderer.render(scene, camera)

       stats.update(); // 每帧更新
    }

    // 启动渲染循环
    animate()

    // 清理函数
    return () => {
      // 移除事件监听器
      document.removeEventListener('pointerlockchange', onPointerLockChange);
      document.removeEventListener('pointerlockerror', onPointerLockError);
      document.removeEventListener('keydown', onKeyDown);
      document.removeEventListener('keyup', onKeyUp);
      renderer.domElement.removeEventListener('click', onCanvasClick);
      window.removeEventListener('resize', handleResize);

      // 清理Three.js资源
      scene.traverse((object) => {
        if (object.geometry) {
          object.geometry.dispose();
        }
        if (object.material) {
          if (Array.isArray(object.material)) {
            object.material.forEach(material => {
              if (material.map) material.map.dispose();
              material.dispose();
            });
          } else {
            if (object.material.map) object.material.map.dispose();
            object.material.dispose();
          }
        }
      });

      // 清理纹理缓存
      textureCache.forEach(texture => texture.dispose());
      textureCache.clear();

      renderer.dispose();

      // 移除DOM元素
      if (containerRef.current && renderer.domElement) {
        containerRef.current.removeChild(renderer.domElement)
      }
    }
  }, [])

  return (
    <div
      ref={scrollContainerRef}
      className='container w-full h-[100vh] overflow-auto hide-scrollbar'
      style={{
        overflowY: 'auto',
        height: '100vh'
      }}
    >
      <div
        ref={containerRef}
        style={{
          position: 'fixed',
          top: 0,
          left: 0,
          width: '100%',
          height: '100%',
          zIndex: 1,
        }}
      />

      {/* 使用说明界面 */}
      <div style={{
        position: 'fixed',
        top: 20,
        left: 20,
        color: 'white',
        backgroundColor: 'rgba(0,0,0,0.7)',
        padding: '10px',
        borderRadius: '5px',
        fontSize: '14px',
        zIndex: 1000,
        pointerEvents: 'none'
      }}>
        <div>点击画面锁定鼠标控制视角</div>
        <div>WASD: 移动 | 空格: 上升 | Shift: 下降</div>
        <div>ESC: 解锁鼠标</div>
      </div>

      {/* 性能监控界面（可选） */}
      <div style={{
        position: 'fixed',
        top: 20,
        right: 20,
        color: 'white',
        backgroundColor: 'rgba(0,0,0,0.7)',
        padding: '10px',
        borderRadius: '5px',
        fontSize: '12px',
        zIndex: 1000,
        pointerEvents: 'none'
      }}>
        <div>性能已优化</div>
        <div>检查控制台查看FPS</div>
      </div>
    </div>
  )
}

export default App